package com.weather.data.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * @author HanYiMing
 * @description
 * @date 2024/12/23
 */
public class SaltUtil {

    // 生成随机盐值
    public static byte[] generateSalt() {
        try {
            SecureRandom secureRandom = SecureRandom.getInstanceStrong();
            byte[] salt = new byte[16];
            secureRandom.nextBytes(salt);
            return salt;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Error generating salt", e);
        }
    }

    // 使用SHA-256算法将密码和盐值结合并生成哈希值
    public static String hashPassword(String password, byte[] salt) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            // 更新盐值到消息摘要
            messageDigest.update(salt);
            // 计算哈希值
            byte[] hashedBytes = messageDigest.digest(password.getBytes());
            // 转换为Base64字符串
            return Base64.getEncoder().encodeToString(hashedBytes);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Error hashing password", e);
        }
    }
}
